#include "library.h"
#include <iostream>
#include <QVBoxLayout>
#include <QProgressBar>
#include <QLabel>

Library::Library(int booksCount): booksCount(booksCount), added(0), closed(false)
{
    setLayout(new QVBoxLayout(this));

    layout()->addWidget(new QLabel("Total books"));
    layout()->addWidget(&booksUsed);
    booksUsed.setRange(0, booksCount);

    layout()->addWidget(new QLabel("Doing something"));
    layout()->addWidget(&doing);
    doing.setRange(0, 0);

    layout()->addWidget(new QLabel("Waiting"));
    layout()->addWidget(&waiting);
    waiting.setRange(0, 0);

    books = new QMutex[booksCount];
}

int Library::getBooksCount()
{
    int result;
    libMutex.lock();
    result = added;
    libMutex.unlock();
    return result;
}

void Library::releaseBook(int index)
{
    libMutex.lock();
    books[index].unlock();
    doing.setValue(doing.value() - 1);
    libMutex.unlock();
}

int Library::addBook()
{
    libMutex.lock();
    if(added == booksCount){
        libMutex.unlock();
        return -1;
    } else {
        int result = added++;
        booksUsed.setValue(added);
        libMutex.unlock();
        return result;
    }
}

void Library::registerPerson()
{
    libMutex.lock();
    ++persons;
    doing.setRange(0, persons);
    waiting.setRange(0, persons);
    libMutex.unlock();
}

void Library::close()
{
    closed = true;
}

bool Library::isClosed()
{
    return closed;
}

bool Library::tryAcquireBook(int index)
{
    int got = books[index].tryLock();
    if(got) {
        libMutex.lock();
        doing.setValue(doing.value() + 1);
        libMutex.unlock();
    }
    return got;
}

void Library::acquireBook(int index)
{
    libMutex.lock();
    waiting.setValue(waiting.value() + 1);
    libMutex.unlock();

    books[index].lock();

    libMutex.lock();
    waiting.setValue(waiting.value() - 1);
    doing.setValue(doing.value() + 1);
    libMutex.unlock();
}
